package com.ijtunes.sources;

import com.ijtunes.utils.Properties;
import com.ijtunes.utils.Property;
import java.io.File;
import java.util.LinkedList;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Iterator;

public class FileCollectionBuilder {

    private LinkedList<File> files = new LinkedList<File>();

    public FileCollectionBuilder(ArrayList<String> locations) {
        for (String startDir : locations) {
            scanFolder(new File(startDir));
        }
    }

    private void scanFolder(java.io.File folder) {
        for (java.io.File file : folder.listFiles(new FilenameFilterImpl())) {
            if (file.isDirectory()) {
                scanFolder(file);
            } else {
                files.add(file);
            }
        }
    }

    public Iterator<File> getIterator() {
        return files.iterator();
    }

    private static class FilenameFilterImpl implements FilenameFilter {

        private static final ArrayList<String> extensions = Properties.getArray(Property.MUSIC_EXTENSIONS);

        public FilenameFilterImpl() {
        }

        @Override
        public boolean accept(File dir, String name) {
            name = name.toLowerCase();
            if (!new File(dir.getPath() + "\\" + name).isDirectory()) {
                try {
                    return (extensions.contains(name.subSequence(name.lastIndexOf('.'), name.length()).toString()));
                } catch (StringIndexOutOfBoundsException oob) {
                    return false;
                }
            } else {
                return true;
            }
        }
    }
}
